import { postLogin } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/authorization'

const state = () => ({
  userid: sessionStorage.getItem('userinfo')
    ? JSON.parse(sessionStorage.getItem('userinfo')).userid
    : NaN,
  avatar: sessionStorage.getItem('userinfo')
    ? JSON.parse(sessionStorage.getItem('userinfo')).avatar
    : '',
  nickname: sessionStorage.getItem('userinfo')
    ? JSON.parse(sessionStorage.getItem('userinfo')).nickname
    : '昵称',
  phone: sessionStorage.getItem('userinfo')
    ? JSON.parse(sessionStorage.getItem('userinfo')).phone
    : '昵称',
  email: sessionStorage.getItem('userinfo')
    ? JSON.parse(sessionStorage.getItem('userinfo')).email
    : '昵称',
  create_time: sessionStorage.getItem('userinfo')
    ? JSON.parse(sessionStorage.getItem('userinfo')).create_time
    : '',
  token: getToken() ? getToken() : ''
})

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
  },
  SET_USERINFO(state, user) {
    state.userid = user.userid
    state.avatar = user.avatar
    state.nickname = user.nickname
    state.phone = user.phone
    state.email = user.email
    state.create_time = user.create_time
  }
}

const actions = {
  login({ dispatch, commit }, account) {
    return new Promise(resolve => {
      postLogin(account).then(res => {
        const data = res.data
        if ('token' in data) {
          try {
            data.avatar = require(`images/avatar/${account.username}.jpg`)
          } catch (err) {
            data.avatar = ''
          }
          dispatch('updateUserinfo', data)
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve(data)
        } else {
          resolve(data)
        }
      })
    })
  },
  updateUserinfo({ commit }, account) {
    const userinfo = {
      userid: account.userid,
      avatar: account.avatar,
      nickname: account.nickname,
      phone: account.phone,
      email: account.email,
      create_time: account.create_time
    }
    sessionStorage.setItem('userinfo', JSON.stringify(userinfo))
    commit('SET_USERINFO', account)
  },
  logout({ commit }) {
    commit('SET_TOKEN', '')
    commit('SET_USERINFO', '')
    sessionStorage.removeItem('userinfo')
    removeToken()
  }
}

export default {
  namespaced: true,
  state,
  actions,
  mutations
}
